package com.ksd.manage;

import com.alibaba.fastjson.JSON;
import com.ksd.pojo.SmbmsBill;
import com.ksd.pojo.SmbmsProvider;
import com.ksd.pojo.SmbmsRole;
import com.ksd.pojo.SmbmsUser;
import com.ksd.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys")
public class Sys {

    @Autowired
    private UserService userService;

    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;

    @Autowired
    private RoleService roleService;


    public static SmbmsUser getUser() {
        return (SmbmsUser) getRequest().getSession().getAttribute(Key.mainUser);
    }

    @RequestMapping("/401")
    public String login() {
        return JspPath.ERR_401;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        return JspPath.LOGIN;
    }

    @RequestMapping("/bill")
    public String bill(@Nullable String productName, @Nullable Long providerId, @Nullable Integer isPayment,@Nullable Integer currentPage,  Map<String, Object> map) {
        List<SmbmsBill> list = billService.getBill(productName, isPayment, providerId);
        List<SmbmsProvider> list1 = providerService.getAllProvider();
        map.put("providerList", list1);
        if (currentPage == null || currentPage.equals(0)) currentPage = 1;
        list=billService.getBill(list,currentPage);
        map.put("billList", list);
        int total = list.size();
        int page = total==0 ? 0:total%10==0?total/10:total/10+1;
        map.put("totalPage", page);
        map.put("totalCount", total);
        if (page == 0) currentPage = 0;
        map.put("currentPage", currentPage);
        return JspPath.BILL_LIST;
    }

    @RequestMapping("/billadd")
    public String billadd() {
        return JspPath.BILL_ADD;
    }

    @RequestMapping("/billview")
    public String billview(Long billid, Map<String, Object> map) {
        SmbmsBill smbmsBill = billService.GetBillOneMessage(billid);
        SmbmsProvider smbmsProvider = providerService.getOneProvider(smbmsBill.getProviderId());
        map.put("bill", smbmsBill);
        map.put("provider", smbmsProvider);
        return JspPath.BILL_VIEW;
    }

    @RequestMapping("/billmodify")
    public String billmodify(Long billid, Map<String, Object> map) {
        SmbmsBill smbmsBill = billService.GetBillOneMessage(billid);
        SmbmsProvider smbmsProvider = providerService.getOneProvider(smbmsBill.getProviderId());
        map.put("bill", smbmsBill);
        map.put("provider", smbmsProvider);
        return JspPath.BILL_MODIFY;
    }

    @ResponseBody
    @RequestMapping(value = "/billselect", method = RequestMethod.GET)
    public String billselect() {
        List<SmbmsProvider> list = providerService.getAllProvider();
        return JSON.toJSONString(list);
    }

    @RequestMapping("/dobillmodify")
    public String dobillmodify(@RequestParam Map<String, String> pmap, Map<String, Object> map) {
        SmbmsBill smbmsBill = billService.VertifyOneMessage(pmap);
        SmbmsProvider smbmsProvider = providerService.getOneProvider(smbmsBill.getProviderId());
        map.put("bill", smbmsBill);
        map.put("provider", smbmsProvider);
        return JspPath.BILL_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/billdel", method = RequestMethod.GET)
    public String billdel(Long billid) {
        BillCode b = billService.RemoveOneBill(billid);
        ResponceResult responceResult = new ResponceResult();
        if (b.equals(BillCode.DEL_FAILURE)) {
            responceResult.setResult("false");
            return JSON.toJSONString(responceResult);
        } else if (b.equals(BillCode.NO_EXIST)) {
            responceResult.setResult("notexist");
            return JSON.toJSONString(responceResult);
        } else if (b.equals(BillCode.NO_PAY)) {
            responceResult.setResult("noPay");
            return JSON.toJSONString(responceResult);
        }
        responceResult.setResult("true");
        return JSON.toJSONString(responceResult);
    }

    @RequestMapping("/dobilladd")
    public String dobilladd(@RequestParam Map<String, String> pmap, Map<String, Object> map) {
        SmbmsUser user = getUser();
        SmbmsBill smbmsBill = billService.AddOneBill(pmap, user.getId());
        return "redirect:/sys/bill";
    }

    @RequestMapping("/provider")
    public String provider(@Nullable String queryProCode,@Nullable Integer currentPage, Map<String, Object> map) {
        List<SmbmsProvider> list = providerService.getProvider(queryProCode);
        if (currentPage == null || currentPage.equals(0)) currentPage = 1;
        list = providerService.getProvider(list, currentPage);
        map.put("proList",list);
        int total = list.size();
        int page = total==0 ? 0:total%10==0?total/10:total/10+1;
        map.put("totalPage", page);
        map.put("totalCount", total);
        if (page == 0) currentPage = 0;
        map.put("currentPage", currentPage);
        return JspPath.PROVIDER_LIST;
    }

    @ResponseBody
    @RequestMapping(value = "/delprovider", method = RequestMethod.GET)
    public String delprovider(Long proid) {
        int len = providerService.removeOneProvider(proid);
        ResponceResult responceResult = new ResponceResult();
        if (len <= 0) {
            responceResult.setResult("false");
            return JSON.toJSONString(responceResult);
        }
        responceResult.setResult("true");
        return JSON.toJSONString(responceResult);
    }

    @RequestMapping("/proview")
    public String proview(Long proid, Map<String, Object> map) {
        SmbmsProvider smbmsProvider = providerService.getOneProvider(proid);
        map.put("provider", smbmsProvider);
        return JspPath.PROVIDER_VIEW;
    }

    @RequestMapping("/providermodify")
    public String providermodify(Long proid, Map<String, Object> map) {
        SmbmsProvider smbmsProvider = providerService.getOneProvider(proid);
        map.put("provider", smbmsProvider);
        return JspPath.PROVIDER_MODIFY;
    }

    @RequestMapping("/providermodifysave")
    public String providermodifysave(@RequestParam Map<String, String> pmap, Map<String, Object> map, HttpServletRequest request) {
        providerService.vertifyOneMessage(pmap);
        return "redirect:/sys/provider";
    }

    @RequestMapping("/provideradd")
    public String provideradd(Map<String, Object> map, HttpServletRequest request) {
        return JspPath.PROVIDER_ADD;
    }

    @RequestMapping("/provideraddsave")
    public String provideraddsave(@RequestParam Map<String, String> pmap) {
        providerService.addOneProvider(pmap);
        return "redirect:/sys/provider";
    }

    @RequestMapping("/providerview")
    public String providerview() {
        return JspPath.PROVIDER_VIEW;
    }

    @RequestMapping("/pwdmodify")
    public String pwdmodify() {
        return JspPath.PWD_MODIFY;
    }

    @RequestMapping("/savepwdmodify")
    public String savepwdmodify(String newpassword, Map<String, Object> map) {
        boolean b = userService.chanagePassword(getUser(), newpassword);
        if (b) map.put("succees", "修改成功");
        else map.put("succees", "修改失败");
        return JspPath.PWD_MODIFY;
    }

    @ResponseBody
    @RequestMapping(value = "/checkpwd", method = RequestMethod.GET)
    public String checkpwd(String oldpassword) {
        ResponceResult responceResult = new ResponceResult();
        if (oldpassword == null || "".equals(oldpassword)) {
            responceResult.setResult("error");
            return JSON.toJSONString(responceResult);
        }
        SmbmsUser user = getUser();
        if (user == null) {
            responceResult.setResult("sessionerror");
            return JSON.toJSONString(responceResult);
        }
        boolean b = userService.verifyUserPwd(user.getId(), oldpassword);
        if (!b) {
            responceResult.setResult("false");
            return JSON.toJSONString(responceResult);
        }
        responceResult.setResult("true");
        return JSON.toJSONString(responceResult);
    }

    @ResponseBody
    @RequestMapping("/getrolelist")
    public String getrolelist() {
        List<SmbmsRole> list = roleService.getAllRole();
        return JSON.toJSONString(list);
    }

    @RequestMapping("/user")
    public String user(@Nullable String queryname, @Nullable Long queryUserRole, @Nullable Integer currentPage, Map<String, Object> map) {
        SmbmsUser user = getUser();
        boolean b = userService.isPermissionToUserCotrol(user);
        if (!b) {
            map.put("notPermission","您没有权限访问用户管理");
            return JspPath.FRAME;
        }
        List<SmbmsRole> list1 = roleService.getAllRole();
        map.put("roleList", list1);
        List<SmbmsUser> list = userService.getUser(queryname, queryUserRole);
        if (currentPage == null || currentPage.equals(0)) currentPage = 1;
        list = userService.getUser(list, currentPage);
        map.put("userList", list);
        int total = list.size();
        int page = total==0 ? 0:total%10==0?total/10:total/10+1;
        map.put("totalPage", page);
        map.put("totalCount", total);
        if (page == 0) currentPage = 0;
        map.put("currentPage", currentPage);
        return JspPath.USER_LIST;
    }

    @RequestMapping("/useradd")
    public String userAdd(Map<String, Object> map) {
        return JspPath.USER_ADD;
    }

    @RequestMapping("/viewUser")
    public String viewUser(@RequestParam Long uid, Map<String, Object> map) {
        SmbmsUser user = userService.getUser(uid);
        SmbmsRole role = roleService.getRole(user.getUserRole());
        map.put("user", user);
        map.put("role", role);
        return JspPath.USER_VIEW;
    }

    @RequestMapping("/saveuser")
    public String saveuser(@RequestParam Map<String, String> pmap, Map<String, Object> map) {
        SmbmsUser smbmsUser = (SmbmsUser) userService.addOneUser(pmap, getUser());
        map.put("user", smbmsUser);
        SmbmsRole role = roleService.getRole(smbmsUser.getUserRole());
        map.put("role", role);
        return JspPath.USER_VIEW;
    }

    @RequestMapping("/modifyUser")
    public String modifyUser(@RequestParam Long uid, Map<String, Object> map) {
        SmbmsUser customer = userService.getUser(uid);
        map.put("user", customer);
        return JspPath.USER_MODIFY;
    }

    @RequestMapping("/modifyusersave")
    public String modifyusersave(@RequestParam Map<String, String> pmap, Map<String, Object> map) {
        SmbmsUser customer = userService.changeOneUser(pmap);
        map.put("user", customer);
        return JspPath.USER_VIEW;
    }


    @ResponseBody
    @RequestMapping("/deleteUser")
    public String deleteUser(@RequestParam Long uid, Map<String, Object> map) {
        ResponceResult responceResult = new ResponceResult();
        UserCode userCode = userService.removeOneUser(uid);
        if (userCode.equals(UserCode.DEL_FAILURE)) {
            responceResult.setResult("false");
            return JSON.toJSONString(responceResult);
        }
        responceResult.setResult("true");
        return JSON.toJSONString(responceResult);
    }
    @ResponseBody
    @RequestMapping("/usercode")
    public String deleteUser(@RequestParam String userCode) {
        ResponceResult responceResult = new ResponceResult();
        boolean b = userService.isExeistUserCode(userCode);
        if (!b) {
            responceResult.setResult("not exist");
            return JSON.toJSONString(responceResult);
        }
        responceResult.setResult("exist");
        return JSON.toJSONString(responceResult);
    }
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    public static HttpServletResponse getRequence() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }


}
